package com.example.loginstarter.service.serviceImpl;

import com.example.loginstarter.domain.LoginUser;
import com.example.loginstarter.domain.ResponseResult;
import com.example.loginstarter.service.LoginService;
import com.example.loginstarter.utils.JwtUtil;
import com.example.loginstarter.utils.RedisCache;
import com.yc.yjh.entity.Users;
import io.jsonwebtoken.Claims;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
public class LoginServiceImpl implements LoginService {


    @Resource
    private AuthenticationManager authenticationManager;

    @Resource
    private RedisCache redisCache;
    @Override
    public ResponseResult login(Users user) {
        //AuthenticationManager进行用户认证
        UsernamePasswordAuthenticationToken authenticationToken=
                new UsernamePasswordAuthenticationToken(user.getUsername(),user.getPassword());
        Authentication authentication=authenticationManager.authenticate(authenticationToken);
        //如果认证通过，给出对应的提示
        if (Objects.isNull(authentication)){
            throw new RuntimeException("登陆失败");
        }
        //认证通过,使用userID生成jwt，jwt传入Result返回
        LoginUser loginUser= (LoginUser) authentication.getPrincipal();
        int userId = loginUser.getUser().getUserId();
        String jwt = JwtUtil.createJWT(String.valueOf(userId));
        //把完整的用户信息存入redis，userId作为key
        Map<String,String> map=new HashMap<>();
        map.put("token",jwt);
        redisCache.setCacheObject("login:"+userId,loginUser);
        return new ResponseResult(200,"登录成功",map);
    }

    @Override
    public ResponseResult logout() {
        //获取用户ID
        UsernamePasswordAuthenticationToken authentication =
                (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        int userId = loginUser.getUser().getUserId();
        //删除redis中的key
        redisCache.deleteObject("login:"+userId);

        return new ResponseResult(200,"注销成功");
    }

    @Override
    public ResponseResult getUserInfo(HttpServletRequest request) {
        String token=request.getHeader("token");
        String userid;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            userid = claims.getSubject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("token非法");
        }
        String redisKey = "login:" + userid;
        LoginUser loginUser = redisCache.getCacheObject(redisKey);
        return new  ResponseResult(200,"查询成功",loginUser);
    }
}
